package com.zr.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.spi.http.HttpContext;

import com.zr.model.User;
import com.zr.service.LoginService;
import com.zr.service.impl.LoginServiceImpl;

import net.sf.json.JSONObject;

public class LoginAction extends HttpServlet {
	private LoginService ls = new LoginServiceImpl();
	public static ServletContext application;
	public static String uuname;
	public static String uupsw;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		PrintWriter pw = resp.getWriter();
		JSONObject json = new JSONObject();
		String uname = req.getParameter("uname");
		String upsw = req.getParameter("upsw");
		String image = req.getParameter("image").toLowerCase();
		String imageInfo = ((String) req.getSession().getAttribute("imageInfo")).toLowerCase();
		if(!imageInfo.equals(image)){
			json.put("success", false);
			json.put("msg", "验证码错误");
		}else{
			//application = this.getServletContext();// 获取application对象
			this.uuname = uname;
			this.uupsw = upsw;
			User user = ls.verificationUser(uname, upsw);
			HttpSession session = req.getSession();
			session.setAttribute("user", user);
			if (user != null) {
				if(user.getRid()!=1){
					json.put("success", false);
					json.put("msg", "您不是系统管理员");
				}else{
					json.put("success", true);
					json.put("msg", "恭喜你成功登录");
				}
			} else {
				json.put("success", false);
				json.put("msg", "很遗憾你用户名或密码错误");
			}
		}
		pw.write(json.toString());
		pw.flush();
	}
}
